// stores/cart.ts
import { defineStore } from 'pinia';

declare interface ISite {
  cart: ICart[]
}
declare interface ICart {
	goods_id: number, 
	goods_name: string, 
	goods_price: number, 
	goods_count: number, 
	goods_small_logo: string, 
	goods_state: boolean
}

const useCartStore_ = defineStore('cart', {
	state: (): ISite => {
		return { 
			// 购物车的数组，用来存储购物车中每个商品的信息对象
			// 每个商品的信息对象，都包含如下 6 个属性：
			// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
			cart: JSON.parse(uni.getStorageSync('cart') || '[]')
		};
	},
	// 也可以这样定义
	// state: () => ({ count: 0 })
	actions: {
		addToCart(goods: ICart) {
			const findResult = this.cart.find(x => x.goods_id === goods.goods_id)

			if (!findResult) {
				this.cart.push(goods)
			} else {
				findResult.goods_count++
			}
			this.saveToStorage()
		},
		saveToStorage() {
			uni.setStorageSync('cart', JSON.stringify(this.cart))
		},
		// 更新购物车中商品的勾选状态
		updateGoodsState(goods) {
			const findResult = this.cart.find(x => x.goods_id === goods.goods_id)

			if (findResult) {
				findResult.goods_state = goods.goods_state

				this.saveToStorage()
			}
		},
		// 更新商品的数量
		updateGoodsCount(goods: ICart) {
			const findResult = this.cart.find(x => x.goods_id === goods.goods_id)

			if (findResult) {
				findResult.goods_count = goods.goods_count

				this.saveToStorage()
			}
		},
		// 根据 Id 删除对应的商品
		removeGoodsById(goods_id: number) {
			this.cart = this.cart.filter(x => x.goods_id !== goods_id)

			this.saveToStorage()
		},
		// 更新购物车中所有商品的勾选状态
		updateAllGoodsState(newState) {
			this.cart.forEach(x => x.goods_state = newState)

			this.saveToStorage()
		}
	},
  getters: {
		// 购物车中所有商品的总数量
		total(): number {
			// let c = 0
			// state.cart.forEach(x => c += x.goods_count)
			// return c
			return this.cart.reduce((total, item) => total += item.goods_count, 0)
		},
		// 购物车中已勾选商品的总数量
		checkedCount(): number {
			return this.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		// 已勾选商品的总价格
		checkedGoodsAmount(): any {
			return this.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0).toFixed(2)
		}
	}
});

export const useCartStore = useCartStore_()
